package geektime.io.netty.homework;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.DecoderResult;
import io.netty.util.CharsetUtil;

/**
 * 模拟服务端处理类
 */
public class DemoServerHandler extends ChannelInboundHandlerAdapter {

    private ByteBuf byteBuf = new UnpooledByteBufAllocator(false).heapBuffer();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Connection established.");
        // 连接成功后给客户端一个响应信息
        byteBuf.writeBytes("220 Netty SMTP Server".getBytes());
        ctx.writeAndFlush(byteBuf);
    }

    // 处理读取事件的方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取客户端过来的数据
        byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.writerIndex()];
        byteBuf.readBytes(bytes);
        String strMsg = new String(bytes);
        System.out.println("C: " + strMsg);
        // 根据情况给客户端响应信息
        if ("QUIT".equalsIgnoreCase(strMsg)) {
            byteBuf.writeBytes("221 Bye".getBytes());
            ctx.writeAndFlush(byteBuf);
            ctx.close();
        } else if ("DATA".equalsIgnoreCase(strMsg)) {
            byteBuf.writeBytes("354 Enter mail, end with \".\" on a line by itself".getBytes());
            ctx.writeAndFlush(byteBuf);
        } else if (".".equals(strMsg)) {
            byteBuf.writeBytes("250 Message sent".getBytes());
            ctx.writeAndFlush(byteBuf);
        } else {
            byteBuf.writeBytes("250 OK".getBytes());
            ctx.writeAndFlush(byteBuf);
        }
    }

    // 读取完毕后的处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
